<template>
	<view style="padding:10upx">
		<canvas class="canvas" canvas-id="myCanvas" @click="onCanvas"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show_num:"",
				code: "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
			};
		},
		methods: {
			draw(show_num) {
				const ctx = uni.createCanvasContext('myCanvas');
				ctx.setFillStyle('#fefefe')
				ctx.fillRect(0,0,100,30)
				for (var i = 0; i < 8; i++) {
					var x = Math.floor(Math.random() * 100);
					var y = Math.floor(Math.random() * 30);
					var x1 = Math.floor(Math.random() * 100);
					var y1 = Math.floor(Math.random() * 30);
				
					ctx.beginPath();
					ctx.setStrokeStyle(this.randomColor());
					ctx.setLineWidth(1);
					ctx.moveTo(x1, y1);
					ctx.lineTo(x, y);
					ctx.stroke();
				}
				ctx.setFontSize(24);
				var arr = show_num.split('');
				var tx = 0;
				arr.forEach((e, i) => {
				tx += 20;
				var ty = Math.floor((Math.random()*4) + 24);
				ctx.setFillStyle(this.randomColor());
				if (e) {
					
					ctx.fillText(e, tx, ty - 0.5);
					ctx.fillText(e, tx - 0.5, ty);
				}
				ctx.fillText(e, tx, ty);
				if (e) {
					ctx.fillText(e, tx, ty + 0.5);
					ctx.fillText(e, tx + 0.5, ty);
				}
				ctx.rotate((0.4-Math.random()) * 0.15);
				});
				ctx.draw();
			},
			//得到随机的颜色值
			randomColor() {
				var r = Math.floor(Math.random() * 256);
				var g = Math.floor(Math.random() * 256);
				var b = Math.floor(Math.random() * 256);	
				return 'rgb(' + r + ',' + g + ',' + b + ')';
			},
		
			onCanvas() {
				this.mathcode();
				var show_num = this.show_num;
				this.draw(show_num);
			},
			mathcode(){
				this.show_num='';
				for (let a = 0; a < 4; a++) {
					console.log(a)
					let index = Math.floor(Math.random() * (this.code.length - 1) + 1);
				    this.show_num +=  this.code[index];
				  }
				  this.$emit('update:choosecode',this.show_num);   //主要
			}
		},
		mounted() {
			this.mathcode();
			var show_num = this.show_num;
			this.draw(show_num);
		}
	}
</script>

<style>
.canvas {
	width: 100px;
	height: 30px;
	border: 1px solid #e5e5e5;
}
</style>
